<?php

namespace App\Http\Controllers\Permission;

use App\Http\Controllers\Controller;
use App\Http\Requests\PaginateRequest;
use App\Http\Requests\Permission\RoleStoreRequest;
use App\Http\Requests\Permission\RoleUpdateRequest;
use App\Models\Permission\Role;
use App\Models\Permission\Permission;

class RoleController extends Controller
{
    public function index(PaginateRequest $request) {
        $searchText = $request->input('searchText');
        $result = Role::query();

        if (!!$searchText) {
            $fields = ['name'];
            Role::buildWhereClause($result, $fields, $searchText);
        }

        return response()->json(Role::pagination($result, $request));
    }

    public function show(Role $role) {
        return response()->json($role->load('permissions'));
    }

    public function store(RoleStoreRequest $request) {
        $role = Role::create($request->input('role'));

        $permissions = $request->input('permissions', []);
        $role->permissions()->sync($permissions);

        return response()->json($role);
    }

    public function update(RoleUpdateRequest $request, Role $role) {
        $role->update($request->input('role'));

        $permissions = $request->input('permissions', []);
        $role->permissions()->sync($permissions);

        return response()->json($role);
    }

    public function destroy(Role $role) {
        return response()->json($role->delete());
    }

    public function getPermissions(PaginateRequest $request) {
        return response()->json(Permission::pagination(Permission::orderBy('feature_name'), $request));
    }
}
